<template>
  <div class="container">
    <div class="login">
      <div class="title">欢迎登录助农服务平台</div>
      <el-form :model="loginParam" label-width="auto" style="max-width: 600px" :rules="rules" ref="form">
        <el-form-item prop="userName">
          <el-input
            v-model="loginParam.userName"
            prefix-icon="user"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginParam.password"
            prefix-icon="lock"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            style="
              width: 100%;
              background-color: rgb(40, 130, 107);
              border-color: rgb(40, 130, 107);
              color: white;
            "
            @click="login"
            ><span>登 录</span></el-button
          >
        </el-form-item>
        <div class="register">
          <div></div>
          <div id="reg2">
            还没有账号？请 <a href="/register">注册</a>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts" name="login">
import { ref,reactive } from "vue";
import { ElMessage } from "element-plus";
import useUserStore from "@/stores/modules/user";
import { useRouter, useRoute } from "vue-router";
let userStore = useUserStore()
//获取路由器对象
let $router = useRouter();
let $route = useRoute();
//获取form组件实例
let form = ref<any>();
// 登录表单
let loginParam = reactive({
  userName:"",
  password:""
})

// 登录按钮的回调
const login = async () => {
  //保证表单校验两项都复合条件
  await form.value.validate();
  try {
    //用户登录成功
    await userStore.userLogin(loginParam);
    // 登录成功后获取用户信息存储于仓库中
    await userStore.getUserInfo()
    //获取url的query参数
    let redirect = $route.query.redirect;
    if (redirect) {
      $router.push(redirect as string);
    } else {
      $router.push("/home");
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message,
    });
  }
}

//表单校验的规则对象
const rules = {
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur"}],
};

</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  overflow: hidden;
  background-image: url("./images/bg2.png");
  background-size: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  .login {
    width: 400px;
    padding: 30px;
    background-color: white;
    border-radius: 5px;
    .title {
      text-align: center;
      font-size: 20px;
      margin-bottom: 20px;
      color: rgb(51, 51, 51);
    }
    .register {
      display: flex;
      div {
        flex: 1;
      }
      #reg2 {
        text-align: right;
        a {
          text-decoration: none;
        }
      }
    }
  }
}
</style>
